package com.ruanda.aspect;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * 记录系统日志AOP
 */
@Component
@Slf4j
@Aspect
public class SysLogAspect {
    
    /**
     * 切入点表达式
     */
    public static final String POINT_CUT = "execution (* com.ruanda.controller.*.*(..))";


    @Around(POINT_CUT)
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = null;
        //获取请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //获取请求路径
        String path = request.getRequestURI();
        //获取ip地址
        String ip = request.getRemoteHost();
        //获取请求参数
        Object[] args = joinPoint.getArgs();
        //获取请求方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String methodName = method.toString();
        //获取注解
        Operation operation = method.getDeclaredAnnotation(Operation.class);
        String operationName = "";
        if(ObjectUtil.isNotNull(operation)){
            operationName = operation.summary();
        }
        String finalArgs = "";
        if(ObjectUtil.isNotNull(args) && args.length != 0 && args[0] instanceof MultipartFile){
            finalArgs = "file";
        }else {
            finalArgs = JSONObject.toJSONString(args);
        }
        //记录开始时间
        long startTime = System.currentTimeMillis();
        try {
            result = joinPoint.proceed(args);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        //记录结束时间
        long endTime = System.currentTimeMillis();
        //方法执行时长
        long time = endTime - startTime;
        
        log.info("调用时间：{}，请求路径：{}，请求ip：{}，请求方法：{}，请求参数：{}，执行时长：{}ms，方法描述：{}"
                ,new Date(),path,ip,methodName,finalArgs,time,operationName);

        return result;
    }

}
